#include <string>
#include <fstream>
#include "Inventory.h"

/*
*	Constructors
*/
Inventory::Inventory(char* filename) {
	getProducts(filename);
} //Inventory

/*
*	Destructor
*/
Inventory::~Inventory() {
	/*
	 * Destroy each product
	 */
	for(int i = 0; i < products.getCount(); ++i)
		delete products.get(i);
} //~Inventory

/*
*	Methods
*/
Product* Inventory::find(int productId) {
	int position = products.getCount() >> 1;
	int search = position;
	int comparison = 0;

	/*
	*	Divide range of search by 2 until the product is found. If comparison is low, go up.
	*	If comparison is high, go down.
	*/
	do {
		if		(comparison > 0) position -= search;
		else if (comparison < 0) position += search;

		if (position < 0 || position >= products.getCount()) {
			comparison = -1;
			break;
		} //if

		search = search >> 1;
		if (!search) search = 1;

		comparison = products.get(position)->getProductNumber() - productId;
	} while (comparison && position > 0 && position < products.getCount());

	/*
	*	If final comparison was a match, return product
	*/
	if (!comparison) return products.get(position);

	return NULL;
} //find

void Inventory::getProducts(char* filename) {
	char buffer[40];
	ifstream inFile(filename);

	Product* product;
	
	if(!inFile.is_open())	throw(INVALID_INVENTORY_FILE);
	
	/*
	*	Pass each line of file to product
	*/
	while(inFile.good()) {
		inFile.getline(buffer, 40);

		if (buffer[0] == '\n' || buffer[0] == '\r' || !buffer[0]) continue;

		/*
		*	Possible errors are overflow from indexed array and invalid product
		*	For simplicity, just state that the inventory file is invalid in either case.
		*	Could go into more detailed errors.
		*
		*	Other errors includes multiples of a product number in a file
		*/
		try {
			product = new Product(buffer);
		} //try
		catch (int) {
			throw(INVALID_INVENTORY_FILE);
		} //catch

		if (find(product->getProductNumber())) {
			duplicates.insert(product->getProductNumber());
			delete product;
			continue;
		} //if

		try {
			products.insert(product);
		} //try
		catch(int) {
			throw(INVALID_INVENTORY_FILE);
		} //catch
	} //while

	inFile.close();
} //getProducts